<?php

namespace EthanZ\HyperfExt\Common;

use Hyperf\Context\Context;

class TraceEntity
{


    /**
     * sql
     *
     * @var array
     */
    private array $sqlDebug = [];

    /**
     * rpc
     *
     * @var array
     */
    private array $rpcDebug = [];

    /**
     * es
     *
     * @var array
     */
    private array $esDebug = [];

    /**
     * 运行开始时间
     *
     * @var float
     */
    private float $requestStartTime = 0;


    /**
     * 传入一个sql
     *
     * @param float  $time
     * @param string $sql
     */
    public function setAnSql(float $time, string $sql)
    {
        $sqlMsg = $time . 'ms ' . $sql;

        $this->sqlDebug[] = $sqlMsg;
    }


    /**
     * 传入一个rpc
     *
     * @param array $backData
     */
    public function setAnRpc(array $backData)
    {
        $rpcBeginTime = $backData['context']['time'] ?? 0;

        $this->rpcDebug[] = [
            'path'  => $backData['context']['path'] ?? '',
            'time'  => $rpcBeginTime ? microtime(true) - $rpcBeginTime : 0,
            'data'  => $backData['result'] ?? [],
            'error' => $backData['error'] ?? [],
        ];
    }


    /**
     * 传入一个es
     *
     * @param array $esDebugData
     */
    public function setAnEs(array $esDebugData)
    {
        $this->esDebug[] = $esDebugData;
    }


    /**
     * 存入初始时间
     *
     * @param float $requestStartTime
     */
    public function setTime(float $requestStartTime)
    {
        $this->requestStartTime = $requestStartTime;
    }


    /**
     * 获取debug信息
     *
     * @return array
     */
    public function getDebugData(): array
    {
        $data['runtime']  = microtime(true) - $this->requestStartTime;
        $data['sqlDebug'] = $this->sqlDebug;
        $data['rpcDebug'] = $this->rpcDebug;
        $data['esDebug']  = $this->esDebug;

        return $data;
    }


    public static function getInstance(): TraceEntity
    {
        if (Context::has(self::class)) {
            return Context::get(self::class);
        } else {
            $self = new self();
            Context::set(self::class, $self);

            return $self;
        }
    }
}